using System;
using System.Linq;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{
	public partial class SimpleSword : ViewController
	{
		private float mCurrentSeconds = 0f;

		private void Update()
		{
			mCurrentSeconds += Time.deltaTime;

			if (mCurrentSeconds >= Global.SimpleSwordDuration.Value)
			{
				mCurrentSeconds = 0f;

				int countTimes = Global.SuperSimpleSword.Value ? 2 : 1;
				int damageTimes = Global.SuperSimpleSword.Value ? Random.Range(2, 4) : 1;
				int distanceTimes = Global.SuperSimpleSword.Value ? 2 : 1;
				
				Enemy[] enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);

				foreach (Enemy enemy in enemies
					         .OrderBy(e => e.Direction2DFrom(Player.Default).magnitude)
					         .Where(e=>e.transform.Direction2DFrom(Player.Default).magnitude <= Global.SimpleSwordRange.Value * distanceTimes)
					         .Take((Global.SimpleSwordCount.Value + Global.AdditionFlyingCount.Value) * countTimes))
				{
					Sword.Instantiate()
						.Position(enemy.Position() + Vector3.left * 0.25f)
						.Show()
						.Self(self =>
						{
							var selfCache = self;
								
							selfCache.OnTriggerEnter2DEvent(collider2d =>
							{
								var hurtBox = collider2d.gameObject.GetComponent<HitHurtBox>();

								if (hurtBox)
								{
									if (hurtBox.Owner.CompareTag("Enemy"))
									{
										DamageSystem.CalculateDamage(Global.SimpleSwordDamage.Value * damageTimes, enemy);
									}
								}
							}).UnRegisterWhenGameObjectDestroyed(selfCache);
								
							// 劈砍动画
							ActionKit.Sequence()
								.Callback(() => selfCache.enabled = false)
								.Parallel(p =>
								{
									p.Lerp(0f, 10f, 0.2f, z =>
									{
										selfCache.transform.LocalEulerAnglesZ(z);
									});

									p.Append(ActionKit.Sequence()
										.Lerp(0f, 1.25f, 0.1f, scale => selfCache.LocalScale(scale))
										.Lerp(1.25f, 1f, 0.1f, scale => selfCache.LocalScale(scale)));
								})
								.Callback(() => selfCache.enabled = true)
								.Parallel(p =>
								{
									p.Lerp(10f, -180f, 0.2f, z =>
									{
										selfCache.transform.LocalEulerAnglesZ(z);
									});

									p.Append(ActionKit.Sequence()
										.Lerp(0f, 1.25f, 0.1f, scale => selfCache.LocalScale(scale))
										.Lerp(1.25f, 1f, 0.1f, scale => selfCache.LocalScale(scale)));
								})
								.Lerp(-180f, 0f, 0.2f, z =>
								{
									selfCache.transform.LocalEulerAnglesZ(z);
									selfCache.LocalScale(z.Abs() / 180);
								})
								.Start(this, () =>
								{
									selfCache.DestroyGameObjGracefully();
								});
						});
				}
			}
		}
	}
}
